/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import dao.DBManager;
import dao.ServiceManager;
import font.MyFont;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.*;
import listener.IDownloadListener;
import model.BackManager;
import model.ErrorMessage;
import model.RecycleData;
import util.StringUtils;
import view.AForm;
import view.MainForm;
import view.MessageForm;
import view.SendSMSForm;
import view.SplashForm;
import view.StyleManager;

/**
 * @author kevin
 */
public class MStockMidlet extends MIDlet {

    public static String PROVIDER = "vsvteam";
    public static String DISPLAY_GRID = "1";
    public static String DISPLAY_LIST = "2";
    
    public static Display display;

    // global data
    private int accent; // default: 2 html code
    private int flag = 4; // default: GPRS Error

    private String applicationId = ""; // application id
    private String money;
    private String days;
    
    private Image background = null, advertise = null; // background
    private Image[] images = new Image[]{null, null, null, null, null, null, null, null, null}; // icon chuc nang
    private Image[] icons = new Image[]{null, null, null, null, null, null, null, null, null, null, null, null, null, null, null}; // icon chuc nang

    private RecycleData recycle;
    private BackManager backManager;
    private MyFont font;
    private StyleManager style;

    private String imagePath = "";
    private String menuView = "";

    // true : show
    // false : delay
    private boolean completed = false;

    public void startApp() {

        display = Display.getDisplay(this);

        // load some configs from database
        loadConfig();

        // load splash screen
        new SplashForm(this, display).show();

        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        // validation
        new Thread() {
            public void run() {
                initCheck();
            }
        }.start();

        // load image
        initData();
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    private void loadConfig() {
//        String st = DBManager.getSetting(DBManager.DB_CONFIG, "ST");
//        String fs = DBManager.getSetting(DBManager.DB_CONFIG, "FS");
//        String mv = DBManager.getSetting(DBManager.DB_CONFIG, "MV");

        // set Style
//        if ((st != null) && (st.trim().length() > 0)) {
//            setStyle(Integer.parseInt(st.trim()));
//        } else {
//            setStyle(StyleManager.STYLE_ORANGE);
//        }

        // set font
//        if ((fs != null) && (fs.trim().length() > 0)) {
//            String[] item = StringUtils.splitAdvance(fs.trim(), ":");

//            if (item.length > 1) {
//                setFont(Integer.parseInt(item[0].trim()), Integer.parseInt(item[1].trim()));
//            } else {
//                setFont(Font2.SIZE12N, Font2.SIZE12B);
//            }
//        } else {
//            setFont(Font2.SIZE12N, Font2.SIZE12B);
//        }
        initFont();

        // set menu
//        if ((mv != null) && (mv.trim().length() > 0)) {
//            setMenuView(mv);
//        } else {
            setMenuView(DISPLAY_GRID);
//        }
    
    }

    private void initData() {
        // load image
        loadImage();

        // create back manager
        backManager = new BackManager();

        // create recycle data
        recycle = new RecycleData();
    }

    private void initFont() {
        font = new MyFont();
    }

    public void setStyle(int iStyle) {
        style = new StyleManager(iStyle);
    }

    public String getMenuView() {
        return menuView;
    }

    public void setMenuView(String menuView) {
        this.menuView = menuView;
    }

    private void loadImage() {
        int i = 0;

        // load background image
        this.background = null;

        // load images of main form
        for (i = 1; i <= 9; i++) {
            try {
                images[i - 1] = Image.createImage(imagePath + i + ".png");
            } catch (java.io.IOException err) {
                images[i - 1] = null;
            }
        }

        // load icons
        for (i = 1; i <= icons.length; i++) {
            try {
                icons[i - 1] = Image.createImage("/image/" + i + ".png");
            } catch (java.io.IOException err) {
                icons[i - 1] = null;
            }
        }
    }

    public void back(int items) {
        if (items > 0) {
            backManager.remove(items);
        }

        String s = backManager.pop().trim();
        if (s.length() > 0) {
            String[] array = StringUtils.splitAdvance(s, ":");

            String obj = array[0];
            String br = "";
            String op = "";

            if (array.length > 2) {
                br = array[1];
                op = array[2];
            }

            if (obj.trim().length() > 0) {
                Class c = null;
                Object o = null;
                try {
                    c = Class.forName(obj.trim());
                    o = c.newInstance();
                } catch (Exception e) {
                    o = null;
                }

                if (o != null) {
                    if (o instanceof AForm) {
                        AForm a = (AForm) o;
                        a.setProperties(this, display);

                        int i = -1, j = -1;

                        if (br.trim().length() > 0) {
                            i = Integer.parseInt(br.trim());
                        }

                        if (op.trim().length() > 0) {
                            j = Integer.parseInt(op.trim());
                        }

                        a.setOption(i, j);
                        a.show();
                    }
                }
            }
        }
    }

    public void initCheck() {
        checkAppCondition();

        if (flag == 1) {
            new MainForm(this, display).show();

        } else if (flag == 0) {
            new SendSMSForm(this, display, SendSMSForm.SEND_MESSAGE, applicationId, money, days).show();

        } else if (flag == 2) {
            new MessageForm(this, display, MessageForm.CONNECTION_DENIED, "", true).show();

        } else if (flag == 3) {
            new MessageForm(this, display, MessageForm.SERVICE_UNAVAILABLE, "", true).show();

        } else if (flag == 4) {
            new MessageForm(this, display, MessageForm.ERROR_GPRS, "", true).show();
        }
    }

    private void checkAppCondition() {
//        String[] data = DBManager.getSettingData(DBManager.DB_CONFIG);
//
//        if (data != null) {
//            String id = data[0];
//            if ((id != null) && (id.trim().length() > 0)) {
//                applicationId = StringUtils.getValue(id.trim(), "=");
//
//                String reinstall = data[1];
//                if ((reinstall != null) && (reinstall.trim().length() > 0)) {
//                    String reinstallValue = StringUtils.getValue(reinstall.trim(), "=");
//                    // check reinstall
//                    checkService(reinstallValue, true);
//                } else {
//                    // check expired
//                    checkService(null, false);
//                }
//            } else {
//                firstUsing();
//            }
//        } else {
//            firstUsing();
//        }
    }

    private void checkService(final String s, final boolean re) {
        ServiceManager.checkExpired(this, accent, PROVIDER, applicationId, s, new IDownloadListener() {

            public void completedAction(Object result) {
                if (result != null) {
                    if (result instanceof ErrorMessage) {
                        ErrorMessage err = (ErrorMessage) result;
                        if (err.getCode() == ErrorMessage.ERROR_GPRS) {
                            flag = 4;
                        } else if (err.getCode() == ErrorMessage.ERROR_DENIED) {
                            flag = 2;
                        } else {
                            flag = 3;
                        }
                    } else {
                        String[] array = (String[]) result;
                        if (array.length > 0) {
                            String s1 = array[0].trim();
                            if (s1.length() > 0) {
                                int i1 = Integer.valueOf(s1).intValue();
                                switch (i1) {
                                    case 0:
                                        String s2 = array[1];
                                        String s3 = array[2];
                                        if ((s2 != null) && (s3 != null) && (s2.trim().length() > 0) && (s3.trim().length() > 0)) {
                                            money = s2.trim();
                                            days = s3.trim();
                                            flag = 0;
                                        } else {
                                            flag = 2;
                                        }
                                        break;
                                    case 1:
                                        if (s != null) {
//                                            DBManager.deleteSetting(DBManager.DB_CONFIG, DBManager.PARA_REINSTALL_TIME);
                                        }
                                        flag = 1;
                                        break;
                                    case 2:
                                        flag = 3;
                                        break;
                                }
                            } else {
                                flag = 3;
                            }
                        } else {
                            flag = 3;
                        }
                    }
                } else {
                    flag = 2;
                }
            }
        });
    }

    private void firstUsing() {
        ServiceManager.checkService(this, this.accent, PROVIDER, new IDownloadListener() {

            public void completedAction(Object result) {
                if (result != null) {
                    if (result instanceof ErrorMessage) {
                        ErrorMessage err = (ErrorMessage) result;
                        if (err.getCode() == ErrorMessage.ERROR_GPRS) {
                            flag = 4;
                        } else if (err.getCode() == ErrorMessage.ERROR_DENIED) {
                            flag = 2;
                        } else {
                            flag = 3;
                        }
                    } else {
                        String[] temp = (String[]) result;
                        if (temp.length > 0) {
                            String id = temp[0].toString().trim();
                            if (id.length() > 0) {
                                applicationId = id;
                                DBManager.update(DBManager.DB_CONFIG, DBManager.PARA_APPLICATION, id);
                                flag = 1;
                            } else {
                                flag = 3;
                            }
                        } else {
                            flag = 3;
                        }
                    }
                } else {
                    flag = 2;
                }
            }
        });
    }

    public Image[] getIcons() {
        return icons;
    }

    public Image[] getImages() {
        return images;
    }

    public Image getBackground() {
        return background;
    }

    public void setBackground(Image background) {
        this.background = background;
    }

    public StyleManager getStyle() {
        return style;
    }

    public Display getDisplay() {
        return display;
    }

    public BackManager getBackManager() {
        return backManager;
    }

    public RecycleData getRecycle() {
        return recycle;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

    public Image getAdvertise() {
        return advertise;
    }

    public void setAdvertise(Image advertise) {
        this.advertise = advertise;
    }

    public boolean isCompleted() {
        return completed;
    }

    public void setCompleted(boolean completed) {
        this.completed = completed;
    }
    
    public String getIdValue() {
        return applicationId;
    }

    public MyFont getFont() {
        return font;
    }

    public void setFont(MyFont font) {
        this.font = font;
    }
}
